package com.jg.xmlSchema2JsonSchema.rules;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.jg.xmlSchema2JsonSchema.xsd.*;
import com.jg.xmlSchema2JsonSchema.xsd.util.EnumItem;
import com.jg.xmlSchema2JsonSchema.xsd.util.XsdUtil;

import java.util.List;

/**
 * @author czg
 */
public class EnumRule extends PropertyRule {

    private XsSimpleType simpleType;

    public EnumRule(ObjectRule parentObjectRule, XsAttribute attribute) {
        // TODO Auto-generated constructor stub
        super(parentObjectRule, attribute);
        simpleType = attribute.getSimpleType();
    }

    public EnumRule(ObjectRule parentObjectRule, XsSimpleType simpleType) {
        // TODO Auto-generated constructor stub
        super(parentObjectRule, null);
        this.simpleType = simpleType;
    }

    @Override
    public JSONObject apply() {
        // TODO Auto-generated method stub
        putType(Constants.O_T_string);
        if (simpleType == null) {
            return jsonObject;
        }
        XsRestriction restriction = simpleType.getRestriction();
        if (restriction == null) {
            return jsonObject;
        }
        List<XsEnumeration> enumerations = restriction.getEnumerations();
        if (CollectionUtil.isEmpty(enumerations)) {
            return jsonObject;
        }
        List<EnumItem> items = CollectionUtil.isNotEmpty(enumerations) ? XsdUtil.enumerationsToEnumItemList(enumerations) : XsdUtil.patternsToEnumItemListArray(attribute.getSimpleType().getRestriction().getPatterns());
        JSONArray valueArray = new JSONArray();
        items.forEach(item -> valueArray.add(item.getValue()));
        jsonObject.put(Constants.K_W_enum, valueArray);
        JSONArray descArray = new JSONArray();
        items.forEach(item -> descArray.add(item.getDesc()));
        jsonObject.put(Constants.K_W_enum_javaEnumDescriptions, descArray);
        return jsonObject;
    }
}
